const gulp = require("gulp");
const clean = require("gulp-clean");
const cleanCSS = require("gulp-clean-css");
const uglify = require("gulp-uglify");
const rev = require("gulp-rev");
const revCollector = require("gulp-rev-collector");
const runSequence = require("run-sequence");
const less = require("gulp-less");
const connect = require("gulp-connect");

gulp.task("clean", function () {
  return gulp.src(["app/dist", "app/rev"]).pipe(clean());
});

gulp.task("less", function () {
  return gulp
    .src("app/dev-less/**/*.less")
    .pipe(less())
    .pipe(gulp.dest("app/styles"));
});
gulp.task("watch", function () {
  gulp.watch(["app/dev-less/**/*.less"], ["less"]);
});

gulp.task("revcss", function () {
  return gulp
    .src(["app/styles/**/*.css"])
    .pipe(cleanCSS({
      compatibility: "ie8"
    }))
    .pipe(rev()) //添加hash后缀
    .pipe(gulp.dest("app/dist/css")) //移动到dist/css
    .pipe(rev.manifest()) //生成文件映射
    .pipe(gulp.dest("app/rev/css")); //将映射文件导出到rev/css
});
gulp.task("revjs", function () {
  return gulp
    .src(["app/javascripts/**/*.js"])
    .pipe(uglify({
      compress: true
    }))
    .pipe(rev()) //添加hash后缀
    .pipe(gulp.dest("app/dist/js")) //移动到dist/js
    .pipe(rev.manifest()) //生成文件映射
    .pipe(gulp.dest("app/rev/js")); //将映射文件导出到rev/js
});

gulp.task("revcollector", function () {
  return gulp
    .src(["app/rev/**/*.json", "app/views/**/*"])
    .pipe(
      revCollector({
        replaceReved: true, //允许替换, 已经被替换过的文件
        dirReplacements: {
          // 模板文件 引入路径替换
          "/styles/": "/css/",
          "/javascripts/": "/js/"
        }
      })
    )
    .pipe(gulp.dest("app/dist/views"));
});

gulp.task("connect", function () {
  connect.server({
    name: "DHAdmin",
    root: "app",
    port: 8280
  });
});

gulp.task("default", function (cb) {
  runSequence(
    "clean",
    ["less", "watch"],
    ["revcss", "revjs"],
    "revcollector",
    "connect",
    cb
  );
});